package com.example.demo.service.system.impl;

import com.example.demo.common.page.PageResult;
import com.example.demo.dto.system.UserDTO;
import com.example.demo.dto.system.UserQueryDTO;
import com.example.demo.entity.system.SysSubsystemField;
import com.example.demo.entity.system.SysUser;
import com.example.demo.entity.system.SysUserFieldValue;
import com.example.demo.mapper.system.SysFieldOptionMapper;
import com.example.demo.mapper.system.SysSubsystemFieldMapper;
import com.example.demo.mapper.system.SysUserFieldValueMapper;
import com.example.demo.mapper.system.SysUserMapper;
import com.example.demo.service.system.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private SysSubsystemFieldMapper fieldMapper;
    
    @Autowired
    private SysUserFieldValueMapper fieldValueMapper;
    
    @Autowired
    private SysFieldOptionMapper optionMapper;

    /**
     * 根据用户名查询用户
     *
     * @param username 用户名
     * @return 用户对象
     */
    @Override
    public SysUser selectUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }
    
    /**
     * 根据ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }
    
    /**
     * 查询用户列表
     *
     * @param user 用户信息
     * @return 用户集合
     */
    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }
    
    /**
     * 分页查询用户列表
     *
     * @param queryDTO 查询参数
     * @return 分页结果
     */
    @Override
    public PageResult<SysUser> selectUserPage(UserQueryDTO queryDTO) {
        long total = userMapper.selectUserCount(queryDTO);
        if (total == 0) {
            return PageResult.empty();
        }
        
        List<SysUser> list = userMapper.selectUserPage(queryDTO);
        return new PageResult<>(list, total, queryDTO);
    }
    
    /**
     * 根据ID查询用户详细信息（包含动态字段）
     *
     * @param userId 用户ID
     * @param systemCode 系统编码
     * @return 用户DTO
     */
    @Override
    public UserDTO selectUserDetail(Long userId, String systemCode) {
        // 查询用户基本信息
        SysUser user = userMapper.selectUserById(userId);
        if (user == null) {
            return null;
        }
        
        UserDTO userDTO = new UserDTO();
        userDTO.setUser(user);
        userDTO.setSystemCode(systemCode);
        
        // 查询动态字段值
        if (StringUtils.hasText(systemCode)) {
            // 查询系统字段定义
            List<SysSubsystemField> fields = fieldMapper.selectFieldsBySystemCode(systemCode);
            if (!fields.isEmpty()) {
                // 查询用户字段值
                List<SysUserFieldValue> fieldValues = fieldValueMapper.selectValuesByUserIdAndSystemCode(userId, systemCode);
                
                // 将字段值转换为Map
                Map<Long, SysUserFieldValue> fieldValueMap = fieldValues.stream()
                        .collect(Collectors.toMap(SysUserFieldValue::getFieldId, v -> v));
                
                // 构建动态字段
                for (SysSubsystemField field : fields) {
                    SysUserFieldValue fieldValue = fieldValueMap.get(field.getId());
                    String value = fieldValue != null ? fieldValue.getFieldValue() : field.getDefaultValue();
                    
                    // 如果是选择类型，获取选项值
                    if (("select".equals(field.getFieldType()) || "radio".equals(field.getFieldType()) || "checkbox".equals(field.getFieldType())) 
                            && fieldValue != null && StringUtils.hasText(fieldValue.getFieldValue())) {
                        userDTO.addDynamicField(field.getFieldKey(), fieldValue.getOptionValue());
                    } else {
                        userDTO.addDynamicField(field.getFieldKey(), value);
                    }
                }
            }
        }
        
        return userDTO;
    }
    
    /**
     * 新增用户
     *
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(UserDTO userDTO) {
        SysUser user = userDTO.getUser();
        user.setCreatedAt(new Date());
        user.setIsDeleted(0);
        
        // 新增用户
        int rows = userMapper.insertUser(user);
        if (rows > 0 && StringUtils.hasText(userDTO.getSystemCode())) {
            // 保存动态字段值
            saveDynamicFields(user.getId(), userDTO.getSystemCode(), userDTO.getDynamicFields());
        }
        
        return rows;
    }
    
    /**
     * 修改用户
     *
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(UserDTO userDTO) {
        SysUser user = userDTO.getUser();
        user.setUpdatedAt(new Date());
        
        // 修改用户
        int rows = userMapper.updateUser(user);
        if (rows > 0 && StringUtils.hasText(userDTO.getSystemCode())) {
            // 删除原有动态字段值
            fieldValueMapper.deleteFieldValueByUserIdAndSystemCode(user.getId(), userDTO.getSystemCode());
            
            // 保存动态字段值
            saveDynamicFields(user.getId(), userDTO.getSystemCode(), userDTO.getDynamicFields());
        }
        
        return rows;
    }
    
    /**
     * 修改用户状态
     *
     * @param userId 用户ID
     * @param status 状态
     * @return 结果
     */
    @Override
    public int updateUserStatus(Long userId, Integer status) {
        return userMapper.updateUserStatus(userId, status);
    }
    
    /**
     * 删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户字段值
        fieldValueMapper.deleteFieldValueByUserId(userId);
        
        // 逻辑删除用户
        return userMapper.deleteUserById(userId);
    }
    
    /**
     * 批量删除用户
     *
     * @param userIds 用户ID数组
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        // 删除用户字段值
        for (Long userId : userIds) {
            fieldValueMapper.deleteFieldValueByUserId(userId);
        }
        
        // 逻辑删除用户
        return userMapper.deleteUserByIds(userIds);
    }
    
    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 用户对象
     */
    @Override
    public SysUser login(String username, String password) {
        SysUser user = userMapper.selectUserByUsername(username);
        if (user != null && password.equals(user.getPassword())) {
            return user;
        }
        return null;
    }
    
    /**
     * 校验用户名是否唯一
     *
     * @param username 用户名
     * @return 结果
     */
    @Override
    public boolean checkUsernameUnique(String username) {
        return userMapper.checkUsernameUnique(username) == 0;
    }
    
    /**
     * 校验手机号是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = user.getId() != null ? user.getId() : 0L;
        return userMapper.checkPhoneUnique(user.getPhone(), userId) == 0;
    }
    
    /**
     * 校验邮箱是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = user.getId() != null ? user.getId() : 0L;
        return userMapper.checkEmailUnique(user.getEmail(), userId) == 0;
    }
    
    /**
     * 保存动态字段值
     *
     * @param userId 用户ID
     * @param systemCode 系统编码
     * @param dynamicFields 动态字段值
     */
    private void saveDynamicFields(Long userId, String systemCode, Map<String, Object> dynamicFields) {
        if (dynamicFields == null || dynamicFields.isEmpty()) {
            return;
        }
        
        // 查询系统字段定义
        List<SysSubsystemField> fields = fieldMapper.selectFieldsBySystemCode(systemCode);
        if (fields.isEmpty()) {
            return;
        }
        
        // 构建字段Key与ID的映射
        Map<String, SysSubsystemField> fieldMap = fields.stream()
                .collect(Collectors.toMap(SysSubsystemField::getFieldKey, f -> f));
        
        // 保存字段值
        List<SysUserFieldValue> fieldValues = new ArrayList<>();
        for (Map.Entry<String, Object> entry : dynamicFields.entrySet()) {
            String fieldKey = entry.getKey();
            Object fieldValue = entry.getValue();
            
            SysSubsystemField field = fieldMap.get(fieldKey);
            if (field != null && fieldValue != null) {
                SysUserFieldValue value = new SysUserFieldValue();
                value.setUserId(userId);
                value.setFieldId(field.getId());
                value.setFieldValue(fieldValue.toString());
                value.setCreatedAt(new Date());
                
                fieldValues.add(value);
            }
        }
        
        if (!fieldValues.isEmpty()) {
            fieldValueMapper.batchInsertFieldValues(fieldValues);
        }
    }
} 